package com.microboom.web;

import java.util.List;

import javax.validation.Valid;

import com.microboom.web.exception.RegisterParameterException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.util.JdbcUtils;
import com.microboom.bean.command.RegisterCommand;
import com.microboom.service.AuthenticationService;
import com.microboom.service.exception.PasswordIncorrectException;
import com.microboom.service.exception.RegisterUserException;
import com.microboom.service.exception.UserExistException;
import com.microboom.service.exception.UsernameNotExistException;

@Controller
public class UserController {

	@Autowired
	private AuthenticationService authenticationService;

	/**
	 * UserController 中只要有方法抛出 UsernameNotExistException 和 PasswordIncorrectException 异常，
	 * 都会触发 exceptionHandler() 方法的执行。
	 * Spring MVC 在调用 exceptionHandler 会，会将触发这个方法执行的那个异常对象，传入该方法。

	@ExceptionHandler({UsernameNotExistException.class, PasswordIncorrectException.class})
	public ModelAndView exceptionHandler(Exception e) {
		ModelAndView mav = new ModelAndView();
		if (e instanceof UsernameNotExistException) {
			mav.setViewName("login");
			mav.addObject("errorMsg", "用户名不存在");
			return mav;
		}

		if (e instanceof PasswordIncorrectException) {
			mav.setViewName("login");
			mav.addObject("errorMsg", "密码不正确");
			return mav;
		}

		mav.setViewName("404");
		return mav;
	}
     */

	@RequestMapping("/login.do")
	public ModelAndView login(@RequestParam String username, @RequestParam String password) {
		ModelAndView mav = new ModelAndView();
		authenticationService.login(username, password);
		mav.setViewName("success");
		mav.addObject("successMsg", "恭喜您，登录成功！");
		return mav;
	}

	@RequestMapping("/reg.do")
	public ModelAndView reg(@Valid RegisterCommand command, BindingResult result) {

		ModelAndView mav = new ModelAndView();

		// step 1: 请求参数的合法性校验
		if (result.hasErrors()) {
			throw new RegisterParameterException("reg", result);
		}
		
		// step 2: 注册
		authenticationService.register(command);
		mav.setViewName("success");
		mav.addObject("successMsg", "恭喜您，注册成功！");

		return mav;
	}

	@RequestMapping("/deleteUser.do")
	public void demo(@RequestParam String username1,
					 @RequestParam String username2) {
		try {
			authenticationService.demo(username1, username2);
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
	}
}
